package com.xsz.controller;

import com.xsz.util.ResultVOUtil;
import com.xsz.vo.ResultVO;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * bsea
 * 导出支部手册为word格式
 */
@RequestMapping("/word")
@Slf4j
@RestController
public class WordController {
    @Value("${fileStoreRootPath}")
    String filePath;


    /**
     * 入门列子
     * @return
     */
    @RequestMapping("new")
    public ResultVO<Map<String, String>> create(){
        try {
            Map<String,String> dataMap = new HashMap<String,String>();
            dataMap.put("f1", "Jerry");
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            //指定模板路径的第二种方式,我的路径是D:/      还有其他方式
            System.out.println("filePath==="+filePath);
            configuration.setDirectoryForTemplateLoading(new File(filePath));

            // 输出文档路径及名称
            File outFile = new File(filePath+File.separator+"test.doc");
            //以utf-8的编码读取ftl文件
            Template t =  configuration.getTemplate("m1.ftl","utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("rs", "success");

        return ResultVOUtil.success(map);
    }


    /**
     *  只有文字的简单个人简介
     * @return
     */
        @RequestMapping("template1")
    public ResultVO<Map<String, String>> createTemplate1(){
        try {
            Map<String,String> dataMap = new HashMap<String,String>();
            dataMap.put("f1", "张三");
            dataMap.put("f2", "男");
            dataMap.put("f3", "1999年1月1日");
            dataMap.put("f4", "汉");
            dataMap.put("f5", "本科");
            dataMap.put("f6", "计算机");
            dataMap.put("f7", "中国");
            dataMap.put("f8", "10000");
            dataMap.put("f9", "1385664464");
            dataMap.put("f10", "今年毕业");
            dataMap.put("f11", "JAVA,数据库");
            dataMap.put("f12", "篮球，乒乓球");
            dataMap.put("f13", "努力");
            dataMap.put("f14", "1年");
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            //指定模板路径的第二种方式,我的路径是D:/      还有其他方式
            System.out.println("filePath==="+filePath);
            configuration.setDirectoryForTemplateLoading(new File(filePath));

            // 输出文档路径及名称
            File outFile = new File(filePath+File.separator+"个人简历.doc");
            //以utf-8的编码读取ftl文件
            Template t =  configuration.getTemplate("m2.ftl","utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("rs", "success");

        return ResultVOUtil.success(map);
    }


    /**
     *  只有图片的简单个人简介
     * @return
     */
    @RequestMapping("template2")
    public ResultVO<Map<String, String>> createTemplate2(){
        try {
            Map<String,String> dataMap = new HashMap<String,String>();
            dataMap.put("f1", "张三");
            dataMap.put("f2", "男");
            dataMap.put("f3", "1999年1月1日");
            dataMap.put("f4", "汉");
            dataMap.put("f5", "本科");
            dataMap.put("f6", "计算机");
            dataMap.put("f7", "中国");
            dataMap.put("f8", "10000");
            dataMap.put("f9", "1385664464");
            dataMap.put("f10", "今年毕业");
            dataMap.put("f11", "JAVA,数据库");
            dataMap.put("f12", "篮球，乒乓球");
            dataMap.put("f13", "努力");
            dataMap.put("f14", "1年");
            dataMap.put("image1", getImageBase("C:\\tmp\\123.png"));
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            //指定模板路径的第二种方式,我的路径是D:/      还有其他方式
            System.out.println("filePath==="+filePath);
            configuration.setDirectoryForTemplateLoading(new File(filePath));

            // 输出文档路径及名称
            File outFile = new File(filePath+File.separator+"个人简历.doc");
            //以utf-8的编码读取ftl文件
            Template t =  configuration.getTemplate("m3.ftl","utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("rs", "success");

        return ResultVOUtil.success(map);
    }



    /**
     *  图片-表格个人简介
     * @return
     */
    @RequestMapping("template3")
    public ResultVO<Map<String, String>> createTemplate3(){
        try {
            Map<String,Object> dataMap = new HashMap<String,Object>();
            dataMap.put("f1", "张三");
            dataMap.put("f2", "男");
            dataMap.put("f3", "1999年1月1日");
            dataMap.put("f4", "汉");
            dataMap.put("f5", "本科");
            dataMap.put("f6", "计算机");
            dataMap.put("f7", "中国");
            dataMap.put("f8", "10000");
            dataMap.put("f9", "1385664464");
            dataMap.put("f10", "今年毕业");
            dataMap.put("f11", "JAVA,数据库");
            dataMap.put("f12", "篮球，乒乓球");
            dataMap.put("f13", "努力");
            dataMap.put("f14", "1年");
            dataMap.put("image1", getImageBase("C:\\tmp\\123.png"));

            List<Map<String,Object>> proList=new ArrayList<Map<String,Object>>();
            Map<String,Object> map1=new HashMap<String,Object>();
            map1.put("name","kris");
            map1.put("mobile","12345678911");
            map1.put("position","员工");

            Map<String,Object> map2=new HashMap<String,Object>();
            map2.put("name","jerry");
            map2.put("mobile","12345678922");
            map2.put("position","经理");

            Map<String,Object> map3=new HashMap<String,Object>();
            map3.put("name","jerry");
            map3.put("mobile","12345678933");
            map3.put("position","老板");

            proList.add(map1);
            proList.add(map2);
            proList.add(map3);

            dataMap.put("proList", proList);

            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            //指定模板路径的第二种方式,我的路径是D:/      还有其他方式
            System.out.println("filePath==="+filePath);
            configuration.setDirectoryForTemplateLoading(new File(filePath));

            // 输出文档路径及名称
            File outFile = new File(filePath+File.separator+"个人简历.doc");
            //以utf-8的编码读取ftl文件
            Template t =  configuration.getTemplate("m4.ftl","utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("rs", "success");

        return ResultVOUtil.success(map);
    }

    /**
     *
     * @param userid
     * @param type 可以根据不同的type，导出不同的手册模板
     * @param response
     * @return
     */
    @RequestMapping("download/{userid}/{type}/{zhibuid}/{userid2}")
    public ResultVO<Map<String, String>> load(@PathVariable("userid") String userid, @PathVariable("type") String type, @PathVariable("zhibuid") String zhibuid, @PathVariable("userid2") String userid2, HttpServletResponse response){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Map<String,String> dataMap = getData();  //获取数据
            System.out.println("***type****"+type);
            System.out.println("***userid****"+userid);
            log.info("***type****"+type+"***userid****"+userid);
            Map<String,Object> dataMap = new HashMap<String,Object>();
            String modename="m1.ftl";
            String tile="支部年度工作计划";
            if("mingzhu_pingyi".equals(type)) {
                dataMap.put("f1", "");
                dataMap.put("f2", " ");
                dataMap.put("f3", " ");
                dataMap.put("f4", " ");
                dataMap.put("f5", " ");
                dataMap.put("f6", " ");
                dataMap.put("f7", " ");
                dataMap.put("formCode", "民主评议党员工作");

//                ZhibuShouceYearlyPlanDTO dto=getSCDTO(userid);
//                dataMap.put("f1", sdf.format(dto.getPlanYear()));
//                dataMap.put("f2", dto.getLostedUsers());
//                dataMap.put("f3", dto.getAttendUsers());
//                dataMap.put("f4", dto.getListedUsers());
//                dataMap.put("f5", dto.getLostedReason());
//                dataMap.put("f6", dto.getTitle());
//                dataMap.put("f7", dto.getContent());
//                dataMap.put("f2", dto.get);
                modename = "m2.ftl";
                tile = "民主评议党员工作";

            }

            //Configuration用于读取ftl文件
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");

            //获取模板所在的路径
//        configuration.setDirectoryForTemplateLoading(new File(filePath));
            configuration.setDirectoryForTemplateLoading(new File(filePath));
            //以utf-8的编码读取ftl文件
            Template t =  configuration.getTemplate(modename,"utf-8");

            String fileName = URLEncoder.encode(tile,"UTF-8") +".doc";
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "utf-8"),10240);
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("rs", "success");

        return ResultVOUtil.success(map);

    }




    //获得图片的base64码

    public String getImageBase(String src) {
        if(src==null||src==""){
            return "";
        }
        File file = new File(src);
        if(!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }
}
